package com.rulin.asp.business.service;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.poi.xssf.usermodel.XSSFPictureData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.rulin.asp.attachment.service.AttachService;
import com.rulin.asp.business.entity.Dictionary;
import com.rulin.asp.business.entity.Page;
import com.rulin.asp.business.entity.Question;
import com.rulin.asp.business.entity.QuestionAdminResultRow;
import com.rulin.asp.business.entity.QuestionMyResultRow;
import com.rulin.asp.business.entity.QuestionParam;
import com.rulin.asp.business.entity.QuestionResultRow;
import com.rulin.asp.business.entity.QuestionStatistics;
import com.rulin.asp.business.mapper.QuestionMapper;
import com.rulin.asp.util.Consists;
import com.rulin.asp.util.Excel;
import com.rulin.asp.util.ExcelUtils;

@Service
public class QuestionService {

	@Autowired
	private QuestionMapper questionMapper;
	
	@Autowired
	private DictionaryService dictionaryService;
	
	@Autowired
	private AttachService attachService;
	
	public int saveQuestion(Question question){
		int i = questionMapper.updateByPrimaryKeySelective(question);
		if(i == 0){
			question.setQuesDiffLevel("1");
			question.setQuesTime(new Date());
			question.setQuesType(Consists.QUES_TYPE_1);
			question.setValid("0");
			questionMapper.insert(question);
		}
		return i;
	}
	
	/**
	 * 退回问题
	 * @param question
	 */
	public void backQuestion(Question question){
		questionMapper.updateByPrimaryKeySelective(question);
	}
	
	/**
	 * 认领问题
	 * @param question
	 */
	public void claimQuestion(Question question){
		int i = questionMapper.updateByPrimaryKeySelective(question);
		if(i == 0){
			questionMapper.insert(question);
		}
		
	}
	
	/**
	 * 根据条件分页查询问题池列表
	 * @param param
	 * @return
	 */
	public Pair<Integer, List<QuestionResultRow>> getQuesListByParam(QuestionParam param){
		Integer total = questionMapper.countQuestionByParam(param);
		Page page = param.getPage();
		page.setTotal(total);
		List<QuestionResultRow> list = questionMapper.selectQuestionByParam(param);
		return Pair.of(total, list);
	}
	
	/**
	 * 根据条件分页查询教师端我的问题列表
	 * @param param
	 * @return
	 */
	public Pair<Integer, List<QuestionMyResultRow>> getMyQuesListByParam(QuestionParam param){
		Integer total = questionMapper.countMyQuestionByParam(param);
		Page page = param.getPage();
		page.setTotal(total);
		List<QuestionMyResultRow> list = questionMapper.selectMyQuestionByParam(param);
		return Pair.of(total, list);
	}
	
	/**
	 * 根据条件分页查询管理员端问题列表
	 * @param param
	 * @return
	 */
	public Pair<Integer, List<QuestionAdminResultRow>> getAdminQuesListByParam(QuestionParam param){
		Integer total = questionMapper.countAdminQuestionByParam(param);
		Page page = param.getPage();
		page.setTotal(total);
		List<QuestionAdminResultRow> list = questionMapper.selectAdminQuestionByParam(param);
		return Pair.of(total, list);
	}
	
	/**
	 * 教师端检索功能查询列表
	 * @param param
	 * @return
	 */
	public Pair<Integer, List<QuestionAdminResultRow>> getTeacherQuesListByParam(QuestionParam param){
		Integer total = questionMapper.countTeacherQuestionByParam(param);
		Page page = param.getPage();
		page.setTotal(total);
		List<QuestionAdminResultRow> list = questionMapper.selectTeacherQuestionByParam(param);
		return Pair.of(total, list);
	}
	
	public Question getQuestion(String quesId){
		Question question = questionMapper.selectByPrimaryKey(quesId);
		List<String> quesPics = questionMapper.selectQuesPics(quesId);
		question.setQuesPics(quesPics);
		if(question.getReplyId() != null ) {
			List<String> replyPics = questionMapper.selectReplyPics(question.getReplyId());
			question.setReplyPics(replyPics);
		}
		return question;
	}
	
	/**
	 * 注销题目
	 * @param ids
	 */
	public void deleteQuestionByQuesIds(List<String> ids){
		questionMapper.deleteQuestionByQuesIds(ids);
	}
	
	/**
	 * 发布题目
	 * @param ids
	 */
	public void publishQuesByQuesIds(List<String> ids){
		questionMapper.updateQuesTypeByQuesIds(ids);
	}
	
	public Excel<QuestionStatistics> getExportTodayQuestionStatistics() throws IOException{
		List<QuestionStatistics> list = questionMapper.staticsTodayQuestion();
		return new Excel<QuestionStatistics>(QuestionStatistics.class,list);
	}
	
	@Transactional
	public void importQuestions(InputStream in, String fileName) throws Exception{
		String model = "ques_book_class";//一级目录
		String model1 = "ques_book_class_1";//二级目录
		String model2 = "ques_book_class_2";//二级目录
		String model3 = "ques_book_class_3";//二级目录
		
		org.javatuples.Pair<List<Map<String, XSSFPictureData>>, List<List<Object>>> bankListByExcel = ExcelUtils.getBankListByExcel(in, fileName);
		List<Map<String, XSSFPictureData>> pictures = bankListByExcel.getValue0();
		List<List<Object>> objList = bankListByExcel.getValue1();
		if(!CollectionUtils.isEmpty(objList)){
			for(int i=0;i<objList.size();i++){
				List<Object> list = objList.get(i);
				if(StringUtils.isBlank((String)list.get(3))){
					continue;
				}
				Question question = new Question();
				String id = UUID.randomUUID().toString();
				question.setQuesId(id);
				question.setQuesTitle((String)list.get(0));
				String value = (String) list.get(1);
				String value2 = (String) list.get(2);
				Dictionary dic = dictionaryService.getByValue(model, value);
				String code = dic.getCode();
				question.setBookClass(code);
				switch (Integer.valueOf(code)) {
				case 1:
					Dictionary dic1 = dictionaryService.getByValue(model1, value2);
					String code1 = dic1.getCode();
					question.setBookSecClass(code1);
					break;
				case 2:
					Dictionary dic2 = dictionaryService.getByValue(model2, value2);
					String code2 = dic2.getCode();
					question.setBookSecClass(code2);
					break;
				case 3:
					Dictionary dic3 = dictionaryService.getByValue(model3, value2);
					String code3 = dic3.getCode();
					question.setBookSecClass(code3);
					break;
				default:
					break;
				}
				question.setQuesDescribe((String)list.get(3));
				String loction = i+1+"-4";
				List<org.javatuples.Pair<String, InputStream>> files = new ArrayList<>();
				for (Map<String, XSSFPictureData> picture : pictures) {
					XSSFPictureData xssfPictureData = picture.get(loction);
					if(xssfPictureData == null){
						continue;
					}
					String partName = xssfPictureData.getPackagePart().getPartName().getName();
					String imgName = partName.substring(partName.lastIndexOf("/")+1);
					InputStream is = xssfPictureData.getPackagePart().getInputStream();
					files.add(org.javatuples.Pair.with(imgName, is));
				}
				attachService.uploadPic(files, id);
				saveQuestion(question);
			}
		}
		
	}
}
